package fishBids.group3.behaviour;

import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import es.upm.agents.ontology.ProductType;
import es.upm.agents.ontology.ToGetAmount;
import es.upm.agents.ontology.ToGetAmountResponse;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;

public class GetAmountBehaviour extends SimpleBehaviour {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6882226240772419465L;
	public GetAmountBehaviour(Agent agent, Codec codec, Ontology ontology, AID bank){
		this.creatorAgent = agent;
		this.codec = codec;
		this.ontology = ontology;
		this.bank = bank;
	}

	/**
	 * 
	 */

	@Override
	public void action() {
		if (!sent){
			//System.out.println("Bidder>>> Sending getAmount QUERY_REF message");
			ToGetAmount toGetAmount = new ToGetAmount();
			ProductType productType = new ProductType();
			productType.setType(Constants.TUNA_TYPE.getType());
			toGetAmount.setProductType(productType);
			Utils.sendMessageWithConcept(ACLMessage.QUERY_REF, codec, ontology, bank, Constants.GET_AMOUNT,
					myAgent, toGetAmount);
			sent = true;
		}

		// Waits for the arrival of an answer
		//System.out.println("Bidder>>> Waiting for a getAmount INFORM or REFUSE message");
		// Receive the message
		MessageTemplate mt = MessageTemplate.and( 
		    	MessageTemplate.MatchLanguage(codec.getName()), 
		    	MessageTemplate.and(MessageTemplate.MatchOntology(ontology.getName()),
		    			MessageTemplate.MatchProtocol(Constants.GET_AMOUNT)));
		ACLMessage msg = creatorAgent.receive(mt);

		if (msg != null) {
			if (msg.getPerformative() == ACLMessage.INFORM) {
				//System.out.println("Bidder>>> receive GetAmount INFORM message from bank");
				ToGetAmountResponse toGetAmountResponse = (ToGetAmountResponse) Utils.extractContent(this.creatorAgent,msg);
//				System.out.println("Bidder>>>>> have " + toGetAmountResponse.getAmount() + " kg in account " +
//						"of type " + toGetAmountResponse.getProductType().getType());
				end = true;
				return;
			}
			if (msg.getPerformative() == ACLMessage.NOT_UNDERSTOOD) {
//				System.out.println(this.creatorAgent.getName()
//						+ " got a NOT_UNDERSTOOD in getMoney, check!!!!! :(");
				end = true;
				return;
			}
			if (msg.getPerformative() == ACLMessage.REFUSE) {
//				System.out.println(this.creatorAgent.getName()
//						+ " got a REFUSE in getAmount, retry sending!!!!! :(");
				return;
			}
		} else{
			block();
		}

	}

	@Override
	public boolean done()

	{
		return end;
	}
	
	/* flag to state if the behaviour stops */
	boolean end = false;
	boolean sent = false;
	/* bank agent */
	AID bank;
	
	/*agent creator of this behaviour*/
	Agent creatorAgent;
	private Codec codec; 
	private Ontology ontology; 	


}
